package syn;

public class DeathLock
{
    public static void main(String[] args)
    {
        Operate p1=new Operate(0,"process1");
        Operate p2=new Operate(1,"process2");
        p1.start();
        p2.start();
    }
}
class ResourceA
{ }
class ResourceB
{ }

class Operate extends Thread
{
    //临界资源
    static ResourceA a=new ResourceA();
    static ResourceB b=new ResourceB();
    int choice;
    String name;
    Operate(int choice,String name)
    {
        this.choice=choice;
        this.name=name;
    }

    public void run()
    {
        super.run();
        try
        {
            getResource();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    private void getResource() throws InterruptedException
    {
        if(choice==0)
        {
            synchronized (a)
            {
                System.out.println(this.name+"获得资源a");
                Thread.sleep(1000);
                synchronized (b)
                {
                    System.out.println(this.name+"获得资源b");
                }
            }
//            解决死锁的方法，避免两个锁
//            synchronized (b)
//            {
//                System.out.println(this.name+"获得资源b");
//            }
        }
        else
        {
            synchronized (b)
            {
                System.out.println(this.name+"获得资源b");
                Thread.sleep(1000);

                synchronized (a)
                {
                    System.out.println(this.name+"获得资源b");
                }
            }
        }
    }
}